import React, { useState, useEffect } from 'react';
import './index.less';
import { Button, Input, Pagination } from 'antd';
import NoData from '@/components/pc/NoData';
import DashboardCard from '@/components/pc/DashboardCard';
import CustomDropdown from '@/components/pc/Dropdown';
import Loading from '@/components/pc/Loading';
import { fetchCameraList } from '@/api/hap';
import { VideoCameraOutlined } from '@ant-design/icons';
import useHikCameraPlayer from '@/hooks/hikCamera/useHikCameraPlayer';  


// 类型定义
interface CameraItem {
    recordCode: string;
    name: string;
    type: string;
    typeName: string;
    cameraIndexCode?: string; // 摄像头编号
    cameraStatus: string;
    cameraStatusName: string;
    longitude?: string;
    latitude?: string;
    unitCode?: string
}

interface SearchParams {
    name: string;
    cameraStatus: string;
}

interface Pagination {
    current: number;
    pageSize: number;
    total: number;
}

const CameraList = () => {
    const [statusOptions] = useState([
        { label: '全部', value: '' },
        { label: '在线', value: '1' },
        { label: '离线', value: '0' },
    ]);
    const [list, setList] = useState<CameraItem[]>([]);
    const [loading, setLoading] = useState(false);
    const [searchParams, setSearchParams] = useState<SearchParams>({
        name: '',
        cameraStatus: ''
    });
    const [pagination, setPagination] = useState<Pagination>({
        current: 1,
        pageSize: 20,
        total: 0
    });
    // 不再需要单独预览弹窗

    const { play } = useHikCameraPlayer();

    // 加载摄像头列表
    const loadCameraList = async () => {
        setLoading(true);
        try {
            const filters = [];
            if (searchParams.name) {
                filters.push({
                    "controlId": "name",
                    "dataType": 2,
                    "spliceType": 1,
                    "filterType": 1,
                    "value": searchParams.name
                });
            }
            if (searchParams.cameraStatus) {
                filters.push({
                    "controlId": "cameraStatus",
                    "dataType": 2,
                    "spliceType": 1,
                    "filterType": 2,
                    "value": searchParams.cameraStatus
                });
            }
            const result = await fetchCameraList(filters, pagination.current, pagination.pageSize);

            setList(result.list);
            setPagination(prev => ({ ...prev, total: result.total }));
        } catch (error) {
            console.error('加载摄像头列表失败:', error);
        } finally {
            setLoading(false);
        }
    };

    // 初始化加载
    useEffect(() => {
        loadCameraList();
    }, [pagination.current]);

    // 处理搜索
    const handleSearch = () => {
        setPagination(prev => ({ ...prev, current: 1 }));
        loadCameraList();
    };

    // 重置搜索
    const handleReset = () => {
        setSearchParams({
            name: '',
            cameraStatus: ''
        });
        setPagination(prev => ({ ...prev, current: 1 }));
    };

    // 处理摄像头点击
    const handleCameraClick = (camera: CameraItem) => {
        console.log('点击摄像头:', camera);
    };

    // 获取状态显示文本
    const getStatusText = (status: string) => {
        let statusClass = '';
        if (status === '1') {
            statusClass = 'online';
        } else if (status === '0') {
            statusClass = 'offline';
        } else if (status === '2') {
            statusClass = 'malfunction';
        }
        const statusMap = {
            'online': '在线',
            'offline': '离线',
            'malfunction': '故障',
        };

        return statusMap[statusClass as keyof typeof statusMap] || statusClass;
    };

    // 获取状态样式类名
    const getStatusClass = (status: string) => {
        let statusClass = '';
        if (status === '1') {
            statusClass = 'online';
        } else if (status === '0') {
            statusClass = 'offline';
        } else if (status === '2') {
            statusClass = 'malfunction';
        }
        return `status-${statusClass}`;
    };

    const handleDropdownChange = (value: string) => {
        setSearchParams(prev => ({ ...prev, cameraStatus: value }));
    };

    // 处理分页变化
    const handlePageChange = (page: number) => {
        setPagination(prev => ({ ...prev, current: page }));
    };

    // 预览摄像头：只用全局播放器，播放到选中窗口
    const previewCameraHandler = (camera: CameraItem, e: React.MouseEvent) => {
        e.stopPropagation();
        play(camera as any);
    };

    return (
        <div className={`camera-monitor-list`}>
            <DashboardCard titles={["视频监控列表"]}>
                <div className='content'>
                    <div className="search-section">
                        <div className="search-row">
                            <div className="search-item">
                                <label>名称：</label>
                                <Input
                                    type="text"
                                    value={searchParams.name}
                                    onChange={(e) => setSearchParams(prev => ({ ...prev, name: e.target.value }))}
                                    placeholder="摄像头名称"
                                />
                            </div>
                            <div className="search-item">
                                <label>运行状态：</label>
                                <CustomDropdown
                                    options={statusOptions}
                                    onChange={handleDropdownChange}
                                    value={searchParams.cameraStatus}
                                    placeholder="请选择"
                                />
                            </div>
                        </div>
                        <div className="search-actions">
                            <Button className="search-btn" onClick={handleSearch}>搜索</Button>
                            <Button className="reset-btn" onClick={handleReset}>重置</Button>
                        </div>
                    </div>
                    <div className="list-container">
                        {loading ? <Loading /> :
                            <>
                                {
                                    list.length === 0 ? <NoData /> : (
                                        <>
                                            <div className="camera-list">
                                                {list.map((camera) => (
                                                    <div
                                                        key={camera.recordCode}
                                                        className={`camera-item`}
                                                        onClick={() => handleCameraClick(camera)}
                                                    >
                                                        <div className="camera-info">
                                                            <div className="camera-name">{camera.name}</div>
                                                            <div className="camera-details">
                                                                {camera?.cameraIndexCode && (
                                                                    <span className="camera-number">设备编号: {camera.cameraIndexCode}</span>
                                                                )}
                                                                <span className={`status ${getStatusClass(camera.cameraStatus)}`}>
                                                                    {getStatusText(camera.cameraStatus)}
                                                                </span>
                                                            </div>
                                                        </div>
                                                        <div className="operator">
                                                            <div
                                                                className='preview'
                                                                title='查看监控'
                                                                onClick={(e) => previewCameraHandler(camera, e)}
                                                            >
                                                                <VideoCameraOutlined />
                                                            </div>
                                                        </div>
                                                    </div>
                                                ))}
                                            </div>
                                            <div className="list-footer">
                                                <Pagination
                                                    simple={{ readOnly: true }}
                                                    showSizeChanger={false}
                                                    showTotal={total => `共 ${total} 条`}
                                                    current={pagination.current}
                                                    total={pagination.total}
                                                    pageSize={pagination.pageSize}
                                                    onChange={handlePageChange}
                                                />
                                            </div>
                                        </>
                                    )
                                }
                            </>
                        }
                    </div>
                </div>

            </DashboardCard >
            {/* 全局播放器弹窗已在 App/Layout 层挂载，无需单独渲染 */}
        </div >
    )
};

export default CameraList;